package org.malred.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.malred.pojo.Configuration;
import org.malred.pojo.MappedStatement;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) {
        try {
            // xxxMapper.xml
            Document document = new SAXReader().read(inputStream);
            // <mapper/>
            Element rootElement = document.getRootElement();
            // namespace
            String namespace = rootElement.attributeValue("namespace");
            String[] sqlType = new String[]{
                    "select", "update", "insert", "delete"
            };
            // <select/> ...
            List<Element> sql_doms = new ArrayList();
            for (int i = 0; i < sqlType.length; i++) {
                List<Element> doms = rootElement.selectNodes("//" + sqlType[i]);
                sql_doms.addAll(doms);
            }
            for (Element element : sql_doms) {
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String parameterType = element.attributeValue("parameterType");
                String sqlTxt = element.getTextTrim();
                // sql信息封装
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setResultType(resultType);
                mappedStatement.setParamterType(parameterType);
                mappedStatement.setSql(sqlTxt);
                // 存入configuration
                configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }

}
